package io.github.wanggit.antrpc.client.config.listeners;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import io.github.wanggit.antrpc.client.config.IConfigChangeListener;
import io.github.wanggit.antrpc.commons.bean.ConfigItem;
import io.github.wanggit.antrpc.commons.config.ConfigChangeTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;

/** Slf4j日志配置级别发生变化的情况 配置 logging.level.io.github.wanggit.antrpc.commons.bean.ConfigItem 指定日志级别 */
@Slf4j
public class Slf4LoggerLevelChangeListener implements IConfigChangeListener {

    private static final String PREFIX = "logging.level.";

    @Override
    public void changed(
            ConfigChangeTypeEnum changeType,
            ConfigItem configItem,
            String oldValue,
            String newValue) {
        String key = configItem.getKey();
        if (key.startsWith(PREFIX)) {
            String className = key.replace(PREFIX, "");
            LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
            if (ConfigChangeTypeEnum.DELETE.equals(changeType)) {
                loggerContext.getLogger(className).setLevel(Level.ERROR);
            } else {
                loggerContext.getLogger(className).setLevel(Level.valueOf(newValue));
            }
        }
    }
}
